import { Dialect, Sequelize } from 'sequelize';
import { CONFIG } from '../config/config';

async function initializeDataBase(): Promise<Sequelize> {
  let sequelize: Sequelize | null = null;
  try {
    const url = `mysql://${CONFIG.USER}:${CONFIG.PWD}@${CONFIG.DBHOST}`;
    sequelize = new Sequelize(url, {
      host: CONFIG.DBHOST,
      dialect: CONFIG.DBTYPE as Dialect,
      //   logging: console.log,
    });

    // 创建数据库（如果不存在）
    await sequelize.query(`CREATE DATABASE IF NOT EXISTS ${CONFIG.DBNAME};`);
    // console.log('Database checked/created successfully');

    // 关闭初始连接
    await sequelize.close();

    // 重新连接到新创建的数据库
    sequelize = new Sequelize(CONFIG.DBNAME, CONFIG.USER, CONFIG.PWD, {
      host: CONFIG.DBHOST,
      dialect: CONFIG.DBTYPE as Dialect,
      //   logging: console.log,
    });
  } catch (err: unknown) {
    // console.error('Error initializing database:', err);
    if (err instanceof Error) {
      throw err;
    }
  } finally {
    if (!sequelize) {
      throw new Error('Failed to initialize database');
    }
    return sequelize;
  }
}

export default initializeDataBase;